<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="company" label="所属公司" required>
        <uni-easyinput placeholder="所属公司" v-model="formData.company" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="contact" label="联系人" required>
        <uni-easyinput placeholder="联系人" v-model="formData.contact" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="phone" label="联系方式" required>
        <uni-easyinput placeholder="联系方式" v-model="formData.phone" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="exchange" label="待测试交易所" required>
        <uni-data-checkbox v-model="formData.exchange" :localdata="formOptions.exchange_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="accountCount" label="测试账号数量" required>
        <picker @change="pickerChange($event, 'accountCount')" :range="formOptions.accountCount_data" :value="formOptions.accountCount_index">
          <view>{{formOptions.accountCount_data[formOptions.accountCount_index] || "请选择..."}}</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="futuresCompany" label="所属期货公司" required>
        <uni-easyinput placeholder="所属期货公司" v-model="formData.futuresCompany" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="futuresContact" label="期货公司对接人" required>
        <uni-easyinput placeholder="期货公司对接人" v-model="formData.futuresContact" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="status" label="申请状态">
        <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="createTime" label="创建时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.createTime"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="updateTime" label="更新时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.updateTime"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="ip" label="提交IP地址">
        <uni-easyinput placeholder="提交IP地址" v-model="formData.ip"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="userAgent" label="用户代理">
        <uni-easyinput placeholder="用户代理" v-model="formData.userAgent"></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/acc.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'acc';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  function numberRange(start, end) {
    return Array.from(new Array(end + 1).keys()).slice(start);
  }

  export default {
    data() {
      let formData = {
        "company": "",
        "contact": "",
        "phone": "",
        "exchange": "",
        "accountCount": 1,
        "futuresCompany": "",
        "futuresContact": "",
        "status": "pending",
        "createTime": null,
        "updateTime": null,
        "ip": "",
        "userAgent": ""
      }
      return {
        formData,
        formOptions: {
          "exchange_localdata": [
            {
              "value": "上期/能源所",
              "text": "上期/能源所"
            },
            {
              "value": "中金所",
              "text": "中金所"
            },
            {
              "value": "大商所",
              "text": "大商所"
            },
            {
              "value": "郑商所",
              "text": "郑商所"
            },
            {
              "value": "广期所",
              "text": "广期所"
            }
          ],
          "accountCount_data": numberRange(1, 100),
          "accountCount_index": null,
          "status_localdata": [
            {
              "value": "pending",
              "text": "pending"
            },
            {
              "value": "approved",
              "text": "approved"
            },
            {
              "value": "rejected",
              "text": "rejected"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      pickerChange(e, name) {
        this.formOptions[name + '_index'] = e.detail.value;
        this.formData[name] = this.formOptions[name + '_data'][e.detail.value];
        this.binddata(name, this.formData[name]);
      },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
